﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SQLite;
using System.Configuration;
using Dapper;
namespace WebsiteLogging.Data
{
	public static class SiteLogDAO
	{
		private static IDbConnection Connection()
		{
			return (IDbConnection)new SQLiteConnection(ConfigurationManager.ConnectionStrings["siteLogConnectionString"].ConnectionString);
		}
		public static void Log()
		{
			IDbConnection cn = null;
			try
			{
				using (cn = Connection())
				{
					cn.Open();
					cn.Execute(@"INSERT INTO sitelog(userName,sitePage,referrer,userAgent,comment) 
								  values(@userName,@sitePage,@referrrer,@userAgent,@comment)",
						 new
						 {
							 @userName = HttpContext.Current.User.Identity.Name,
							 sitePage = HttpContext.Current.Request.Url.AbsolutePath,
							 referrrer = HttpContext.Current.Request.UrlReferrer == null ? string.Empty : HttpContext.Current.Request.UrlReferrer.AbsoluteUri,
							 userAgent = HttpContext.Current.Request.UserAgent,
							 comment = ""
						 });
					cn.Close();
				}

			}
			catch (Exception ex)
			{
				//TODO: add error logging here
				HttpContext.Current.Trace.Write(ex.Message);
			}
			finally
			{
				if (cn != null)
				{
					cn.Close();
				}
			}
		}
		public static List<SiteLog> ShowLog()
		{
			List<SiteLog> siteLogList = new List<SiteLog>();
			IDbConnection cn = null;
			try
			{
				using (cn = Connection())
				{
					cn.Open();
					siteLogList = cn.Query<SiteLog>("Select * from sitelog order by datetime desc").ToList();
					cn.Close();
				}

			}
			catch (Exception ex)
			{
				//TODO: add error logging here
			}
			finally
			{
				if (cn != null)
				{
					cn.Close();
				}
			}
			return siteLogList;
		}
	}
}